package com.smartcruise.task;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.smartcruise.base.FragmentActivitySimpleImp;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.main.mainFragment.tools.SosFragment;
import com.smartcruise.main.mainFragment.tools.map.MapActivity;
import com.smartcruise.report.ReportDataEditActivity;
import com.smartcruise.util.Key;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.network.TaskUpload;
import com.smartcruise.util.network.callBack.BaseCallBack;
import com.smartcruise.util.network.callBack.SimpleCallBack;
import com.smartcruise.util.network.netUtils.NetCollection;
import com.smartcruise.util.network.netUtils.NetStatusUtils;
import com.smartcruise.util.network.netUtils.Result;

import java.util.Calendar;
import java.util.Date;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/3/4 0004
 */

public class TaskWithMapPresenterImp implements TaskWithMapContract.Presenter {

    private TaskWithMapContract.View mView;
    private CruiseData cruiseData;
    private Calendar calendar;//如果不为空 则表示查看的是指定日期的任务 为空的话查看的是当天的任务

    public TaskWithMapPresenterImp(TaskWithMapContract.View mView, CruiseData cruiseData, Calendar calendar) {
        this.mView = mView;
        this.cruiseData = cruiseData;
        this.calendar = calendar;
    }

    @Override
    public void start() {

    }

    @Override
    public void clickOnRightText() {
        if (cruiseData.isFromNet()) {
            String[] strings = new String[]{"切换地图模式"};
            final NormalListDialog normalListDialog = new NormalListDialog(mView.getActivity(), strings);
            normalListDialog.title("更多操作");
            normalListDialog.layoutAnimation(null);
            normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            mView.showMapModelList();
                            break;
                    }
                    normalListDialog.dismiss();
                }
            });
            normalListDialog.show();
            return;
        }
        if (CruiseContract.TASK_IS_RUNNING.equals(cruiseData.getStatusInApp())) {//当前处于运行状态
            String[] strings = new String[]{"暂停任务", "结束任务", "切换地图模式"};
            final NormalListDialog normalListDialog = new NormalListDialog(mView.getActivity(), strings);
            normalListDialog.title("更多操作");
            normalListDialog.layoutAnimation(null);
            normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            CruiseContract.pauseTask(cruiseData, mView.getRealm());
                            break;
                        case 1:
                            endTask();
                            break;
                        case 2:
                            mView.showMapModelList();
                            break;
                    }
                    normalListDialog.dismiss();
                }
            });
            normalListDialog.show();
        } else if (CruiseContract.TASK_IS_PAUSE.equals(cruiseData.getStatusInApp())) {//当前处于暂停
            String[] strings = new String[]{"继续任务", "结束任务", "切换地图模式"};
            final NormalListDialog normalListDialog = new NormalListDialog(mView.getActivity(), strings);
            normalListDialog.title("更多操作");
            normalListDialog.layoutAnimation(null);
            normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            if (hasStartedTask()) {
                                mView.showToast("不能同时执行两项任务,请先暂停或结束其他正在执行的任务");
                                return;
                            }
                            CruiseContract.restartTask(cruiseData, mView.getRealm());
                            break;
                        case 1:
                            endTask();
                            break;
                        case 2:
                            mView.showMapModelList();
                            break;
                    }
                    normalListDialog.dismiss();
                }
            });
            normalListDialog.show();
        } else {
            String[] strings = new String[]{"切换地图模式"};
            final NormalListDialog normalListDialog = new NormalListDialog(mView.getActivity(), strings);
            normalListDialog.title("更多操作");
            normalListDialog.layoutAnimation(null);
            normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            mView.showMapModelList();
                            break;
                    }
                    normalListDialog.dismiss();
                }
            });
            normalListDialog.show();
        }
    }

    private void endTask() {
        if (cruiseData.checkContent()) {
            final NormalDialog normalDialog = new NormalDialog(mView.getActivity());
            normalDialog.content("确认结束任务?")
                    .btnText("结束", "取消")
                    .setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                            CruiseContract.endTask(cruiseData, mView.getRealm());
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                        }
                    });
            normalDialog.show();
        } else {
            final NormalDialog normalDialog = new NormalDialog(mView.getActivity());
            normalDialog.content("存在节点任务数据不完善,确认结束任务?")
                    .btnText("结束", "取消")
                    .setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                            CruiseContract.endTask(cruiseData, mView.getRealm());
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                        }
                    });
            normalDialog.show();
        }
    }

    private void changeStatus(final String status) {
        mView.getRealm().executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                cruiseData.setStatusInApp(status);
            }
        });
    }

    @Override
    public void clickOnTaskOverview() {
        TaskDetailsActivity.start(mView.getActivity(), cruiseData.getId(), calendar);
    }

    @Override
    public void clickOnSOS() {
        FragmentActivitySimpleImp.start(mView.getActivity(), SosFragment.class);
    }

    @Override
    public void clickOnReport() {
        ReportDataEditActivity.start(mView.getActivity(), cruiseData.getId());
    }

    @Override
    public void clickOnNavigation() {
        mView.getActivity().startActivity(new Intent(mView.getActivity(), MapActivity.class));
    }

    @Override
    public void clickOnBottomButton() {
        if (!cruiseData.isCopyData() && !cruiseData.isFromNet()) {//新任务
            mView.showToast("该任务尚未到达执行时间,请返回上一级界面刷新后重试");
        } else {
            switch (cruiseData.getStatusInApp()) {
                case CruiseContract.TASK_IS_WAIT_START:
                    if (!TimeUtils.isSameDay(new Date(TimeUtils.currentTime()), new Date(cruiseData.getShouldRunDate()))) {
                        mView.showToast("不是当天的任务,不能开始");
                        return;
                    }
                    if (hasStartedTask()) {
                        mView.showToast("不能同时执行两项任务,请先暂停或结束其他正在执行的任务");
                        return;
                    }
                    refreshData();
                    break;
                case CruiseContract.TASK_IS_PAUSE:
                    CruiseContract.restartTask(cruiseData, mView.getRealm());
                    break;
                case CruiseContract.TASK_IS_END:
                    checkData();
                    break;
                default:
                    mView.showToast("未定义状态:" + cruiseData.getStatusInApp());
            }
        }
    }

    /**
     * description:判断是否已经有在执行的任务
     */

    private boolean hasStartedTask() {
        CruiseData first = mView.getRealm().where(CruiseData.class)
                .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                .equalTo(Key.isCopyData, true)
                .equalTo(Key.isFromNet, false)
                .equalTo(Key.statusInApp, CruiseContract.TASK_IS_RUNNING)
                .findFirst();
        return first != null;
    }

    private void refreshData() {
        NetCollection.getOneNewTask(mView, cruiseData.getPatrollingTaskId(), new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                if (cruiseData.isValid()) {
                    startTask();
                }
            }

            @Override
            public void onFail(Result result) {
                startTask();
            }

            @Override
            public void onError(Throwable e) {
                startTask();
            }
        });
    }

    private void startTask() {
        mView.getActivity().getWindow().getDecorView().post(new Runnable() {//这么做是避免主线程里的数据和其他线程里的数据不同步
            @Override
            public void run() {
                if (cruiseData.isCanStart()) {
                    CruiseContract.startTask(cruiseData, mView.getRealm());
                    mView.showToast("任务已经开始");
                } else {
                    NormalDialog normalDialog = new NormalDialog(mView.getActivity());
                    normalDialog.title("任务未达到开始时间");
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("任务的开始时间是:")
                            .append(TimeUtils.getSimpleTimeString(cruiseData.getShouldRunDate()))
                            .append("\n")
                            .append("您最早可以提前一个小时开始任务,当前不允许开始任务!");
                    normalDialog.content(stringBuilder.toString())
                            .show();
                }
            }
        });
    }

    private void checkData() {
        if (cruiseData.checkContent()) {
            uploadData();
        } else {
            final NormalDialog normalDialog = new NormalDialog(mView.getActivity());
            normalDialog.title("信息不完善")
                    .content("存在节点任务数据不完善,是否继续上传?");
            normalDialog.btnText("上传", "继续完善");
            normalDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    uploadData();
                    normalDialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    normalDialog.dismiss();
                }
            });
            normalDialog.show();
        }
    }

    private void uploadData() {
        if (NetStatusUtils.isConnected(mView.getActivity())) {
            if (NetStatusUtils.isWifi(mView.getActivity())) {//wifi环境下 全部上传
                uploadData(true);
            } else {//不是WiFi的时候 如果有大文件要上传 提醒用户 让其选择
                if (cruiseData.isHaveBigLocalFile()) {
                    final NormalDialog normalDialog = new NormalDialog(mView.getActivity());
                    normalDialog.content("当前使用的是数据流量,上传全部文件会消耗较多流量,是否仅上传概要数据?")
                            .btnText("上传全部数据", "上传概要数据")
                            .setOnBtnClickL(new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    uploadData(true);
                                    normalDialog.dismiss();
                                }
                            }, new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    uploadData(false);
                                    normalDialog.dismiss();
                                }
                            });
                    normalDialog.show();
                } else {
                    uploadData(true);
                }
            }
        } else {
            mView.showToast("网络异常,请检查网络状况");
        }
    }

    private void uploadData(final boolean all) {
        TaskUpload taskUpload = new TaskUpload(cruiseData, mView);
        BaseCallBack baseCallBack = new SimpleCallBack(mView) {
            @Override
            public void onSuccess(Result result) {
                mView.showToast("上传成功");
            }
        };
        if (all) {
            taskUpload.uploadAll(baseCallBack);
        } else {
            taskUpload.uploadSimple(baseCallBack);
        }

    }

}
